// postmoments 页面的逻辑
Page({
  data: {
    content: '',  // 动态文本
    imagePaths: [],  // 选择的图片路径
    userID: ''  // 用户ID
  },

  onLoad: function() {
    try {
      const userInfo = wx.getStorageSync('userInfo');
      if (!userInfo) {
        throw new Error('userInfo 不存在');
      }
      console.log('读取到的 userInfo:', userInfo);

      // 检查 userInfo 是否包含 usersID
      if (!userInfo.usersID) {
        throw new Error('usersID 不存在');
      }

      this.setData({
        userID: userInfo.usersID  // 使用 usersID 作为键名
      });
    } catch (e) {
      console.error(e);
      wx.showToast({
        title: '用户未登录或信息不完整',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 2000);
      return;
    }
  },
  inputContent: function(e) {
    this.setData({
      content: e.detail.value
    });
  },

  chooseImage: function() {
    const that = this;
    wx.chooseImage({
      count: 5 - that.data.imagePaths.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        res.tempFilePaths.forEach(filePath => {
          // 包含存储桶名称的路径
          const cloudPath = `photos-1329147778/my-image-${Date.now()}-${Math.floor(Math.random() * 1000)}.png`;
          wx.cloud.uploadFile({
            cloudPath,
            filePath,
            success: uploadRes => {
              // fileID 将包含存储桶名称，例如："cloud://photos-1329147778/your-file-path"
              that.setData({
                imagePaths: that.data.imagePaths.concat([uploadRes.fileID])
              });
            },
            fail: function(err) {
              console.error('上传失败', err);
            }
          });
        });
      },
      fail: function(err) {
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
        console.error('选择图片失败', err);
      }
    });
  },
  

  postMoment: function() {
    const { content, imagePaths, userID } = this.data;
    if (!content.trim()) {
      wx.showToast({
        title: '文本不能为空',
        icon: 'none'
      });
      return;
    }
    if (imagePaths.length === 0) {
      wx.showToast({
        title: '至少添加一张图片',
        icon: 'none'
      });
      return;
    }
    wx.cloud.callFunction({
      name: 'postMoments',
      data: {
        content,
        imageUrls: imagePaths,
        userID
      },
      success: function(res) {
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        });
        wx.navigateBack();
      },
      fail: function(err) {
        wx.showToast({
          title: '发布失败',
          icon: 'none'
        });
        console.error('发布失败', err);
      }
    });
  }
});